package com.example.module_common.base

import android.content.Context
import android.content.Intent
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import butterknife.ButterKnife
import butterknife.Unbinder
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.example.module_common.R
import com.example.module_common.utils.SettingUtil
import com.example.module_common.utils.StatusBarUtils
import com.example.module_common.weight.LoadingDialog
import com.example.module_common.utils.StatusBarUtil

/**
 * 基类 njb
 *
 * @param <P>
</P> */
abstract class BaseActivity<P : BasePresenter<*>> : AppCompatActivity(), BaseView {
    lateinit var context: Context
    var toast: Toast? = null
    protected var presenter: P? = null

    private var waitDialog: LoadingDialog? = null

    protected abstract val layoutId: Int

    protected abstract fun createPresenter(): P

    protected abstract fun initView()

    protected abstract fun addListener()
    /**
     * theme color
     */
    private var mThemeColor: Int = SettingUtil.getColor()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ARouter.getInstance().inject(this)
        setStatusBar()
        if (layoutId != 0) {
            setContentView(layoutId)
        }
        context = this
        presenter = createPresenter()
        initView()
        addListener()
    }

    protected open fun setStatusBar() {
//        //设置状态栏颜色;
        //setColorForSwipeBack(this, ContextCompat.getColor(this, R.color.white), 0)
////        //亮色
//        StatusBarUtils.StatusBarDarkMode(this, StatusBarUtils.StatusBarLightMode(this));
////        //暗色
        //StatusBarUtils.StatusBarLightMode(this, StatusBarUtils.StatusBarLightMode(this))
    }


    fun setStatusBar(view: View?) {
        if (view == null) {
            return
        }
        val params = ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, StatusBarUtils.getStatusBarHeight(context))
        view.layoutParams = params
        view.background = ColorDrawable()
    }

    /**
     * 打开Activity
     *
     * @param cls
     */
    fun startA(cls: Class<*>) {


        val intent = Intent(context, cls)
        startActivity(intent)
    }

    override fun onResume() {
        super.onResume()
        initColor()
    }

    public override fun onPause() {
        super.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (presenter != null) {
            presenter
        }
    }

    fun initToolBar(title: String): Toolbar? {

        val toolbar = findViewById<Toolbar>(R.id.toolbar)
        if (toolbar != null) {
            setSupportActionBar(toolbar)
            val toolbarTitle = findViewById<TextView>(R.id.toolbar_title)
            toolbarTitle.text = title
        }
        val actionBar = supportActionBar
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true)
            actionBar.setDisplayShowTitleEnabled(false)
        }
        return toolbar
    }

    fun initToolBarAsHome(title: String): Toolbar? {

        val toolbar = findViewById<Toolbar>(R.id.toolbar)
        if (toolbar != null) {
            setSupportActionBar(toolbar)
            val toolbarTitle = findViewById<TextView>(R.id.toolbar_title)
            toolbarTitle.text = title
        }
        val actionBar = supportActionBar
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(false)
            actionBar.setDisplayShowTitleEnabled(false)
        }
        return toolbar
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            android.R.id.home -> {
                onBackPressed()
            }
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onBackPressed() {
        super.onBackPressed()
        // Fragment 逐个出栈
        val count = supportFragmentManager.backStackEntryCount
        if (count == 0) {
            super.onBackPressed()
        } else {
            supportFragmentManager.popBackStack()
        }
    }

    open fun initColor() {
        mThemeColor = if (!SettingUtil.getIsNightMode()) {
            SettingUtil.getColor()
        } else {
            ContextCompat.getColor(context,R.color.colorPrimary)
        }
        StatusBarUtil.setColor(this, mThemeColor, 0)
        if (this.supportActionBar != null) {
            this.supportActionBar?.setBackgroundDrawable(ColorDrawable(mThemeColor))
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            window.statusBarColor = CircleView.shiftColorDown(mThemeColor)
//            // 最近任务栏上色
//            val tDesc = ActivityManager.TaskDescription(
//                    getString(R.string.app_name),
//                    BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher),
//                    mThemeColor)
//            setTaskDescription(tDesc)
          /*  if (SettingUtil.getNavBar()) {
                window.navigationBarColor = CircleView.shiftColorDown(mThemeColor)
            } else {
                window.navigationBarColor = Color.BLACK
            }*/
        }
    }

    /**
     * @param s
     */
    fun showtoast(s: String) {
        Toast.makeText(context, s, Toast.LENGTH_SHORT).show()
    }

    fun showFileDialog() {}

    fun hideFileDialog() {}

    /**
     * 显示加载框
     *
     * @param textRes
     * @param color
     */
    fun showWaitDialog(textRes: String, color: Int) {
        if (null == waitDialog) {
            waitDialog = LoadingDialog(this, textRes, color)
        } else {
            waitDialog!!.setShowText(textRes)
            if (!waitDialog!!.isShown) {
                waitDialog!!.showUp()
            }
        }
    }

    /**
     * 显示加载框
     */
    fun showWaitDialog() {
        if (null == waitDialog) {
            waitDialog = LoadingDialog(this)
        } else {
            waitDialog!!.setShowText("")
            if (!waitDialog!!.isShown) {
                waitDialog!!.showUp()
            }
        }
    }

    /**
     * 显示progressBar
     *
     * @param textRes 需要提示的字
     */
    fun showWaitDialog(textRes: Int) {
        if (null == waitDialog) {
            waitDialog = LoadingDialog(this, textRes)
        } else {
            waitDialog!!.setShowText(textRes)
            if (!waitDialog!!.isShown) {
                waitDialog!!.showUp()
            }
        }
    }

    /**
     * 销毁progressBar
     */
    fun dismissWaitDialog() {
        if (null != waitDialog && waitDialog!!.isShown) {
            waitDialog!!.dismiss()
        }
    }


    /**
     * 通过资源res获得view
     *
     * @param res
     * @return
     */
    fun getViewByRes(@LayoutRes res: Int): View {
        return LayoutInflater.from(context).inflate(res, null)
    }

    /**
     * 获得TextView 的文本
     *
     * @param tv
     * @return
     */
    fun getTV(tv: TextView?): String {
        return tv?.text?.toString()?.trim { it <= ' ' } ?: ""
    }

    override fun showError(msg: String) {
        showtoast(msg)
    }

    override fun onErrorCode(model: BaseModel<Any>) {
        when {
            model.errorCode < 0 -> showtoast(model.errorMsg!!)
        }
    }

    override fun showLoadingFileDialog() {
        showWaitDialog()
    }

    override fun hideLoadingFileDialog() {
        dismissWaitDialog()
    }

    override fun onProgress(totalSize: Long, downSize: Long) {}

    fun addFragmentToActivity(fragmentManager: FragmentManager,
                              fragment: Fragment, frameId: Int) {
        val transaction = fragmentManager.beginTransaction()
        if (!fragment.isAdded)
            transaction.add(frameId, fragment)
        fragmentManager.fragments.filter { it.id == fragment.id }.map { transaction.hide(it) }
        transaction.show(fragment)
        transaction.commit()
    }

}
